<template>
	<view class="create-coupon">
		<view class="coupon-title">使用情况概览</view>
		<!-- 使用率KPI -->
		<view class="use-rate-kpi-box">
			<view class="use-rate-item">
				<view class="use-rate-value">{{couponUsedRateData.rate}}%</view>
				<view class="use-rate-title">使用率</view>
			</view>
			<view class="use-rate-item">
				<view class="use-rate-value">{{couponUsedRateData.send}}</view>
				<view class="use-rate-title">发放数</view>
			</view>
			<view class="use-rate-item">
				<view class="use-rate-value">{{couponUsedRateData.used}}</view>
				<view class="use-rate-title">使用数</view>
			</view>
		</view>

		<!-- 近期领取核销情况KPI -->
		<view class="recent-coupon-kpi-box">
			<view class="header-search-box">
				<view class="quik-date-screen" @click="datePopShow = true">
					<text class="quik-date-text">{{dateRangeValue}}</text>
					<van-icon class="quik-date-arrow" name="arrow" />
				</view>
				<view class="date-range">
					<uni-datetime-picker v-model="couponDate" type="daterange" :clear-icon="false" :border="false"
						@change="couponRangeClick" />
				</view>
			</view>

			<view class="chart-content-box">
				<qiun-data-charts type="column" :opts="opts" :chartData="chartData" :ontouch="true" />
			</view>
		</view>

		<view class="coupon-title">修改卡券信息</view>
		<!-- 修改基本信息、批次数量 -->
		<view class="create-project-form">
			<!-- <view class="create-item">
				<text class="info-item-title">卡券名称</text>
				<input class="info-item-input" type="text" maxlength="21" placeholder-class="placeholderFontClass"
					placeholder="例如:x月x日活动券" v-model="couponName">
			</view> -->

			<!-- <view class="create-item">
				<text class="info-item-title">卡券类型</text>
				<input class="info-item-input" type="text" @click="handleOpenTypePopup"
					placeholder-class="placeholderFontClass" disabled readonly placeholder="请选择卡券类型"
					v-model="couponTypeSelected">
				<uni-icons class="right-arrow-icon" type="forward" size="14" color="#999"></uni-icons>
			</view>

			<view class="create-item" v-if="couponType == 'NORMAL'">
				<text class="info-item-title">优惠金额</text>
				<input class="info-item-input" type="number" placeholder-class="placeholderFontClass"
					placeholder="单位:分;1元=100分" v-model="discount_amount">
			</view>

			<view class="create-item" v-if="couponType == 'DISCOUNT'">
				<text class="info-item-title">折扣比例</text>
				<input class="info-item-input" type="number" placeholder-class="placeholderFontClass"
					placeholder="示例值:86,则为八六折" v-model="discount_percent">
			</view>

			<view class="create-item" v-if="couponType == 'EXCHANGE'">
				<text class="info-item-title">单品换购价</text>
				<input class="info-item-input" type="number" placeholder-class="placeholderFontClass"
					placeholder="单位:分;1元=100分" v-model="exchange_price">
			</view>

			<view class="create-item" v-if="couponType == 'NORMAL' || couponType == 'DISCOUNT'">
				<text class="info-item-title">消费门槛</text>
				<input class="info-item-input" type="number" placeholder-class="placeholderFontClass"
					placeholder="单位:分;1元=100分" v-model="transaction_minimum">
			</view> -->



			<view class="create-item">
				<text class="info-item-title">适用范围</text>
				<input class="info-item-input" type="text" maxlength="15" placeholder-class="placeholderFontClass"
					placeholder="例如:xxx 商品使用" v-model="useRange">
			</view>

			<!-- <view class="create-item">
				<text class="info-item-title">生效时间</text>
				<picker mode="date" :value="startValidDate" :start="startDateLimit" :end="endDateLimit"
					@change="bindStartDateChange">
					<view class="date-picker" :class="{'placeholder-text': startValidDate == '有效期最长为1年'}">
						{{startValidDate}}
					</view>
				</picker>
			</view>

			<view class="create-item">
				<text class="info-item-title">失效时间</text>
				<picker mode="date" :value="endValidDate" :start="failureStartDateLimit" :end="failureEndDateLimit"
					@change="bindEndDateChange">
					<view class="date-picker" :class="{'placeholder-text': endValidDate == '有效期最长为1年'}">
						{{endValidDate}}
					</view>
				</picker>
			</view> -->

			<view class="create-item">
				<text class="info-item-title">发放数量</text>
				<input class="info-item-input" type="number" placeholder-class="placeholderFontClass"
					placeholder="请输入发放数量" v-model="sendNum">
			</view>

			<!-- <view class="create-item">
				<text class="info-item-title">用户可领数量</text>
				<input class="info-item-input" type="number" placeholder-class="placeholderFontClass"
					placeholder="每个用户最多100张券" v-model="receiveNum">
			</view> -->

			<view class="create-item-column">
				<text class="info-item-title">卡券备注</text>
				<uni-easyinput class="info-item-textarea" maxlength="20" type="textarea" v-model="remark"
					placeholder-class="placeholderFontClass" placeholder="用于自定义信息,仅自己可见,字数上限为20个"></uni-easyinput>
			</view>

		</view>

		<button class="create-btn" @click.stop.prevent="handleCreate">确认修改</button>

		<view class="height"></view>

		<!-- 卡券类型popup -->
		<van-popup :show="couponTypePopShow" position="bottom">
			<van-picker show-toolbar :columns="couponTypeList" @confirm="onCouponTypeConfirm"
				@cancel="couponTypePopShow = false" />
		</van-popup>

		<!-- 近期核销卡券时间范围popup -->
		<van-popup :show="datePopShow" position="bottom">
			<van-picker show-toolbar :columns="dateRangeList" @confirm="onDateConfirm" @cancel="datePopShow = false" />
		</van-popup>
	</view>
</template>

<script>
	import apiRqs from '@/api/api-request.js';
	import getDateTime from '@/common/getDateTime.js';
	export default {
		data() {
			return {
				stock_id: "",
				couponInfo: {},
				couponName: "", // 卡券名称
				useRange: "", // 卡券适用范围
				couponType: "", // 卡券类型
				couponTypeSelected: "",
				couponTypePopShow: false,
				couponTypeList: ['固定面额满减券', '折扣券', '换购券'],
				startValidDate: "有效期最长为1年",
				endValidDate: "有效期最长为1年",
				sendNum: "", // 发放数量
				receiveNum: "", // 可领数量
				remark: "", // 卡券备注
				startDateLimit: "", // 生效开始时间限制
				endDateLimit: "", // 生效结束时间限制
				failureStartDateLimit: "", // 失效开始时间限制
				failureEndDateLimit: "", // 失效结束时间限制
				discount_amount: "", // 优惠金额
				discount_percent: "", // 折扣比例
				exchange_price: "", // 单品换购价
				transaction_minimum: "", // 消费门槛
				couponDate: [], // 查询近期核销券时间筛选
				datePopShow: false,
				dateRangeValue: "近7天",
				dateRangeList: ['近7天', '近15天', '近30天'],
				opts: {
					color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
						"#ea7ccc"
					],
					padding: [15, 15, 0, 5],
					touchMoveLimit: 24,
					enableScroll: true,
					legend: {},
					xAxis: {
						disableGrid: true,
						scrollShow: true,
						itemCount: 4
					},
					yAxis: {
						data: [{
							min: 0
						}]
					},
					extra: {
						column: {
							type: "group",
							width: 15,
							activeBgColor: "#000000",
							activeBgOpacity: 0.08
						}
					}
				},
				chartData: {},
				couponUsedRateData: {},
			}
		},
		onReady() {},
		onLoad(options) {
			let stock_id = options.id;
			this.stock_id = stock_id;
			this.handleSearchConfirm(stock_id);
			// 默认取近7天日期
			let cur_date = getDateTime.getDay(-1);
			let pre7_date = getDateTime.getDay(-7);
			this.couponDate = [pre7_date, cur_date];

			this.handleRecentCouponKPI(stock_id, pre7_date, cur_date);
			this.handleCouponUsedRate();
		},
		methods: {
			// 卡券使用率KPI
			handleCouponUsedRate() {
				apiRqs._getCouponUsedRate(this.stock_id).then(res => {
					console.log('卡券使用率', res);
					let newData = JSON.parse(JSON.stringify(res.data));
					if (res.code == 200) {
						this.couponUsedRateData = newData[0];
					} else {
						getApp().showToast(res.msg);
					}
				})
			},
			// 近期核销情况日期选择确认
			couponRangeClick(e) {
				this.couponDate[0] = e[0] + " 00:00:00";
				this.couponDate[1] = e[1] + " 00:00:00";
				console.log('近期核销情况日期选择:', e);
				this.handleRecentCouponKPI(this.stock_id, e[0], e[1]);
			},
			onDateConfirm(e) {
				// 判断选中的时间，给筛选器赋值并刷新图表数据
				let cur_date = getDateTime.getDay(-1);
				if (e.detail.value == '近7天') {
					let pre7_date = getDateTime.getDay(-7);
					this.couponDate = [pre7_date, cur_date];
					this.handleRecentCouponKPI(this.stock_id, pre7_date, cur_date);
				} else if (e.detail.value == '近15天') {
					let pre15_date = getDateTime.getDay(-15);
					this.couponDate = [pre15_date, cur_date];
					this.handleRecentCouponKPI(this.stock_id, pre15_date, cur_date);
				} else if (e.detail.value == '近30天') {
					let pre30_date = getDateTime.getDay(-30);
					this.couponDate = [pre30_date, cur_date];
					this.handleRecentCouponKPI(this.stock_id, pre30_date, cur_date);
				}
				this.dateRangeValue = e.detail.value;
				this.datePopShow = false;
			},
			// 查询卡券
			handleSearchConfirm(stock_id) {
				getApp().showLoading();
				apiRqs._handleQueryCoupon(stock_id).then((res) => {
					uni.hideLoading();
					console.log('查询结果', res);
					if (res.code == 200 && res.data.resultCode.stateCode == 200) {
						const data = JSON.parse(JSON.stringify(res.data));
						// 处理时间格式为微信请求要求格式
						data.coupon_use_rule.coupon_available_time.available_begin_time = data.coupon_use_rule
							.coupon_available_time.available_begin_time.split("T")[0];
						data.coupon_use_rule.coupon_available_time.available_end_time = data.coupon_use_rule
							.coupon_available_time.available_end_time.split("T")[0];

						this.couponInfo = data;
						this.couponName = data.stock_name;
						this.couponType = data.stock_type;

						if (data.stock_type == 'NORMAL') {
							this.couponTypeSelected = '固定面额满减券';
							this.discount_amount = data.coupon_use_rule.fixed_normal_coupon.discount_amount;
							this.transaction_minimum = data.coupon_use_rule.fixed_normal_coupon
								.transaction_minimum;
						} else if (data.stock_type == 'DISCOUNT') {
							this.couponTypeSelected = '折扣券';
							this.discount_percent = data.coupon_use_rule.discount_coupon.discount_percent;
							this.transaction_minimum = data.coupon_use_rule.discount_coupon
								.transaction_minimum;
						} else if (data.stock_type == 'EXCHANGE') {
							this.couponTypeSelected = '换购券';
							this.exchange_price = data.coupon_use_rule.exchange_coupon.exchange_price;
							this.transaction_minimum = data.coupon_use_rule.exchange_coupon
								.transaction_minimum;
						}
						this.useRange = data.goods_name;
						this.startValidDate = data.coupon_use_rule.coupon_available_time.available_begin_time;
						this.endValidDate = data.coupon_use_rule.coupon_available_time.available_end_time;
						this.sendNum = data.stock_send_rule.max_coupons;
						this.receiveNum = data.stock_send_rule.max_coupons_per_user;
						this.remark = data.comment;
					} else {
						getApp().showToast(res.data.resultCode.errorMessage);
					}
				})
			},
			// 获取当前日期戳
			getCurDateNum() {
				const cur_date = getDateTime.dateTimeStr('y-m-d h:i:s');
				const date = cur_date.split(" ")[0];
				const time = cur_date.split(" ")[1];
				const year = date.split("-")[0];
				const month = date.split("-")[1];
				const day = date.split("-")[2];
				const hour = time.split(":")[0];
				const min = time.split(":")[1];
				const sec = time.split(":")[2];
				return year + month + day + hour + min + sec;
			},
			// 打开卡券类型
			handleOpenTypePopup() {
				this.couponTypePopShow = true;
			},
			// 确认卡券类型
			onCouponTypeConfirm(val) {
				this.couponTypePopShow = false;
				const value = val.detail.value;
				if (value == '固定面额满减券') {
					this.couponType = 'NORMAL';
				} else if (value == '折扣券') {
					this.couponType = 'DISCOUNT';
				} else if (value == '换购券') {
					this.couponType = 'EXCHANGE';
				}
				this.couponTypeSelected = value;
				console.log('已选卡券类型', this.couponType);
			},
			// 确认修改
			handleCreate() {
				let {
					couponName,
					remark,
					useRange,
					couponType,
					startValidDate,
					endValidDate,
					discount_amount,
					discount_percent,
					exchange_price,
					transaction_minimum,
					sendNum,
					receiveNum,
				} = this;
				if (couponName == "") {
					getApp().showToast('卡券名称不能为空');
					return false;
				} else if (useRange == "") {
					getApp().showToast('适用范围不能为空');
					return false;
				} else if (sendNum == '' || sendNum == 0) {
					getApp().showToast('发放数量须≥1');
					return false;
				}
				const cur_date = this.getCurDateNum();
				const tokenInfo = uni.getStorageSync("tokenInfo");
				let Randnum = '';
				for (var i = 0; i < 10; i++) {
					Randnum += Math.ceil(Math.random() * 10);
				};
				// 商家券基本信息
				const rqsData = {
					"stock_id": this.couponInfo.stock_id,
					"comment": remark,
					"goods_name": useRange,
					"custom_entrance": {
						"mini_programs_info": {
							"mini_programs_appid": "wxadc26d832d9c62d2",
							"mini_programs_path": "/packageA/workbench/workbench",
							"entrance_words": "欢迎选购",
							"guiding_words": "获取更多优惠"
						},
						"appid": "wxadc26d832d9c62d2",
						"hall_id": "",
						"code_display_mode": "BARCODE"
					},
					"out_request_no": tokenInfo.shopId + cur_date + "01",
					"display_pattern_info": {
						"description": `仅支持在${tokenInfo.shopName}使用`,
						"background_color": "Color020",
						"coupon_image_url": "",
						"finder_info": {
							"finder_id": "sph6Rngt2T4RlUf",
							"finder_video_cover_image_url": "",
							"finder_video_id": "export/UzFfAgtgekIEAQAAAAAAb4MgnPInmAAAAAstQy6ubaLX4KHWvLEZgBPEwIEgVnk9HIP-zNPgMJofG6tpdGPJNg_ojtEjoT94"
						}
					},
					"coupon_use_rule": {
						"use_method": "OFF_LINE",
						// "mini_programs_appid": "wxadc26d832d9c62d2",
						// "mini_programs_path": "/packageA/workbench/workbench"
					},
					"stock_send_rule": {
						"prevent_api_abuse": true
					},
					"notify_config": {
						"notify_appid": "wxadc26d832d9c62d2"
					}
				};
				console.log('修改商家券基本信息', rqsData);
				console.log('修改商家券基本信息json', JSON.stringify(rqsData));

				// 商家券批次预算
				const couponBudget = {
					"target_max_coupons": sendNum * 1,
					// "target_max_coupons_by_day": 0,
					"current_max_coupons": this.couponInfo.stock_send_rule.max_coupons,
					// "current_max_coupons_by_day": 0,
					"modify_budget_request_no": Randnum,
				};
				console.log('修改商家券批次预算', couponBudget);
				getApp().showLoading();
				let p1 = new Promise((resolve) => {
					apiRqs._editCouponInfo(rqsData, this.couponInfo.stock_id).then((res) => {
						console.log('修改商家券基本信息结果', res);
						resolve(res);
					})
				})

				let p2 = new Promise((resolve) => {
					apiRqs._editCouponBudget(couponBudget, this.couponInfo.stock_id).then((res) => {
						console.log('修改商家券批次预算结果', res);
						resolve(res);
					})
				})

				Promise.all([p1, p2]).then(result => {
					uni.hideLoading();
					getApp().showToast("修改成功");
					console.log('result', result);
				}).catch(err => {
					uni.hideLoading();
					getApp().showToast(err);
					console.log('err', err);
				})

			},
			// 有效开始时间
			bindStartDateChange(e) {
				const value = e.detail.value;
				// 选中开始时间后，结束时间最长为1年
				const endDate = getDateTime.handleGetAssignDay(value, 365);
				console.log('+1年时间', endDate);
				this.failureEndDateLimit = endDate;
				if (this.endValidDate != "有效期最长为1年") {
					this.endValidDate = "有效期最长为1年";
				}
				this.startValidDate = value;
				this.failureStartDateLimit = value;
			},
			// 有效结束时间
			bindEndDateChange(e) {
				const value = e.detail.value;
				// 选中开始时间后，结束时间-开始时间最长为1年
				const startDate = getDateTime.handleGetAssignDay(value, -365);
				console.log('-1年时间', startDate);
				if (this.startValidDate == "有效期最长为1年") {
					this.startDateLimit = startDate;
				}
				this.endValidDate = value;
				this.endDateLimit = value;
			},
			// 卡券近期领取、核销KPI
			handleRecentCouponKPI(stock_id, begin_date, end_date) {
				getApp().showLoading();
				let rqsData = {
					"stockId": stock_id,
					"date": {
						"beginDate": begin_date,
						"endDate": end_date
					}
				};
				apiRqs._getRecentCouponKPI(rqsData).then(res => {
					uni.hideLoading();
					console.log('卡券近期领取、核销KPI', res);
					let newData = JSON.parse(JSON.stringify(res.data));
					for (let i = 0; i < newData.xAxis.length; i++) {
						newData.xAxis[i] = newData.xAxis[i].split("-")[1] + "-" + newData.xAxis[i].split("-")[2];
					}
					// 近期领取、核销KPI图表数据
					let chartData = {
						categories: newData.xAxis,
						series: newData.series
					};
					this.chartData = JSON.parse(JSON.stringify(chartData));
				})
			},
		},
	}
</script>

<style lang="less">
	page {
		background-color: #f5f5f5;
	}

	.create-coupon {
		.height {
			height: 30px;
		}

		.coupon-title {
			font-size: 12px;
			color: rgba(0, 0, 0, 0.5);
			display: flex;
			align-items: center;
			margin: 20px 20px 0 20px;

			&::before {
				display: inline-block;
				content: "";
				width: 10px;
				height: 10px;
				border-radius: 50%;
				background-color: #FFA53D;
				margin-right: 10px;
			}
		}

		.use-rate-kpi-box {
			background-color: #fff;
			border-radius: 4px;
			margin: 20px;
			display: flex;
			align-items: center;
			padding: 15px 10px;
			box-sizing: border-box;

			.use-rate-item {
				flex: 1;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				margin: 0 5px;

				.use-rate-value {
					font-size: 20px;
					color: rgba(0, 0, 0, 1);
					font-weight: 600;
				}

				.use-rate-title {
					font-size: 12px;
					color: rgba(0, 0, 0, 0.3);
					margin-top: 5px;
				}
			}
		}

		.recent-coupon-kpi-box {
			margin-top: 20px;

			.header-search-box {
				margin: 0 20px;
				display: flex;
				align-items: center;

				.quik-date-screen {
					width: 55px;
					flex: 0 0 55px;
					display: flex;
					align-items: center;
					justify-content: space-between;

					.quik-date-text {
						font-size: 13px;
						color: rgba(0, 0, 0, 0.3);
					}

					.quik-date-arrow {
						font-size: 10px;
						color: rgba(0, 0, 0, 0.3);
						margin-left: 2px;
						transform: rotate(90deg);
					}
				}

				.date-range {
					flex: 1;
					min-width: 0;
					margin-left: 5px;
				}
			}

			.chart-content-box {
				margin: 20px;
				background-color: #fff;
				border-radius: 4px;
				padding: 10px;
				box-sizing: border-box;
			}
		}

		.create-project-form {
			margin: 20px;

			.create-item {
				display: flex;
				align-items: center;
				width: 100%;
				border-bottom: 1px solid #f5f5f5;
				background-color: #fff;
				padding: 16px 15px;
				box-sizing: border-box;
				position: relative;

				.right-arrow-icon {
					position: absolute;
					right: 10px;
				}

				&:first-child {
					border-top: 1px solid #f5f5f5;
					border-top-left-radius: 4px;
					border-top-right-radius: 4px;
				}

				&:last-child {
					border-bottom-left-radius: 4px;
					border-bottom-right-radius: 4px;
				}

				.info-item-title {
					width: 100px;
					flex: 0 0 100px;
					font-size: 14px;
					margin-right: 10px;
				}

				.date-picker {
					font-size: 14px;
					color: #666;

					&.placeholder-text {
						color: #ddd;
					}
				}

				.info-item-input {
					flex: 1;
					font-size: 14px;
					text-align: left;
					color: #666666;
				}

				.placeholderFontClass {
					color: #ddd;
				}
			}

			.create-item-column {
				display: flex;
				flex-direction: column;
				width: 100%;
				border-bottom: 1px solid #f5f5f5;
				background-color: #fff;
				padding: 16px 15px;
				box-sizing: border-box;
				position: relative;

				.right-arrow-icon {
					position: absolute;
					right: 10px;
				}

				.info-item-title {
					width: 100px;
					font-size: 14px;
					margin-right: 10px;
				}

				.date-picker {
					font-size: 14px;
					color: #666;

					&.placeholder-text {
						color: #ddd;
					}
				}

				.info-item-input,
				.uni-easyinput {
					flex: 1;
					font-size: 14px;
					text-align: left;
					color: #666666;
					margin-top: 10px;

					.is-input-border {
						border-color: #f5f5f5 !important;
					}
				}



				.placeholderFontClass {
					color: #ddd;
				}
			}
		}

		.create-btn {
			margin: 20px;
			border: none;
			background-color: #FFA53D;
			color: #fff;
			font-size: 15px;
			height: 35pt;
			line-height: 35pt;
			box-shadow: inset 0px 4px 7px 0px rgba(255, 255, 255, 0.33);

			&::after {
				border: none;
			}

			&:active {
				background-color: #0076DB;
			}
		}
	}
</style>